import { useEffect, useMemo, useRef, useState } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import { IReducerState, IRootReducerState } from '@/store/root-reducer';
import {
  Button,
  Popconfirm,
  Space,
  Table,
  Image,
  Tag,
  Tooltip,
} from '@douyinfe/semi-ui';
import { IconDeleteStroked, IconEditStroked } from '@douyinfe/semi-icons';
import { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { PaginationProps } from '@douyinfe/semi-ui/lib/es/pagination';
import { usePageContext } from '../context';
import TablePagination, {
  onPageParamsChange,
} from '@/widgets/table-pagination';
import { pageSizeOpts } from '../helper';
import BaseColumns from './columns';
import { useDispatch } from 'react-redux';
import {
  deleteItem,
  fetchItems,
} from '@/redux/application/application-actions';
import { getItemIcon } from '@/redux/application/application-api';
import { AppIcon } from './icon';

const ApplicationTable = () => {
  const dispatch = useDispatch<any>();
  const PageContext = usePageContext();
  const [mouseEnterIndex, setMouseEnterIndex] = useState<any>(null);
  // const mouseEnterIndex = useRef<any>(null);
  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
      addRecord: PageContext.addRecord,
      editRecord: PageContext.editRecord,
      delRecord: PageContext.delRecord,
      detailRecord: PageContext.detailRecord,
    };
  }, [PageContext]);

  const { application } = useSelector<IRootReducerState, any>(
    (state) => ({ application: state.application }),
    shallowEqual
  );
  // entities
  const { totalCount, entities } = application;

  const columns: ColumnProps[] = useMemo(() => {
    return [
      {
        title: '客户端编号',
        dataIndex: 'clientId',
      },
      {
        title: '应用名称',
        dataIndex: 'title',
        render: (content) => {
          return <span className='fw-bold'>{content}</span>;
        },
      },
      {
        title: '应用图标',
        dataIndex: 'icon',
        render: (content) => {
          return content ? <AppIcon fileName={content} /> : <span>暂无</span>;
        },
      },
      {
        title: '应用状态',
        dataIndex: 'status',
        render: (cellContent) => {
          return (
            <Tag color={cellContent === 1 ? 'red' : 'green'}>
              {cellContent === 1 ? '关闭' : '开启'}
            </Tag>
          );
        },
      },
      {
        title: '托管类型',
        dataIndex: 'managedTypeName',
      },
      {
        title: '可重定向的URL地址',
        width: 250,
        dataIndex: 'redirectUris',
        render: (cellContent) => {
          return cellContent ? (
            <Tooltip
              content={cellContent.map((item: any, idx: number) => {
                return (
                  <Tag
                    size='small'
                    shape='circle'
                    color='white'
                    key={idx}
                    className='mr-2 mb-1'
                  >
                    {item}
                  </Tag>
                );
              })}
            >
              <div className='truncate' style={{ width: '250px' }}>
                {cellContent.map((item: any, idx: number) => {
                  return (
                    <Tag
                      size='small'
                      shape='circle'
                      key={idx}
                      className='mr-2 mb-1'
                    >
                      {item}
                    </Tag>
                  );
                })}
              </div>
            </Tooltip>
          ) : (
            <span>暂无</span>
          );
        },
      },
      {
        title: '应用类型',
        dataIndex: 'categoryName',
      },
      ...BaseColumns,
      {
        title: '操作',
        width: 120,
        dataIndex: 'action',
        render: (text, record, index) => {
          // console.log(mouseEnterIndex.current, index);
          return (
            <Space>
              <Button
                icon={<IconEditStroked />}
                onClick={() => {
                  PageAction.editRecord(record[application.key]);
                }}
              ></Button>
              <Popconfirm
                title='删除应用'
                content='确定删除该应用?'
                onConfirm={() => {
                  dispatch(deleteItem(record[application.key])).then(
                    (res: any) => {
                      dispatch(fetchItems(PageAction.queryParams));
                    }
                  );
                }}
              >
                <span className='inline-block invisible group-hover/item:visible'>
                  <Button
                    icon={<IconDeleteStroked style={{ color: '#ef4444' }} />}
                    onClick={() => {
                      // PageAction.delRecord(record[application.key]);
                    }}
                  ></Button>
                </span>
              </Popconfirm>
            </Space>
          );
        },
        // // 此处从render的第四个形参中解构出 展开按钮、选择按钮、文本等内容
        // render: (text, record, index, { expandIcon, selection, indentText }) => {
        //   return <>111</>;
        // })
      },
    ];
  }, []);

  const paginationOptions = useMemo(
    () => ({
      total: totalCount,
      queryParams: PageAction.queryParams,
      pageSizeOpts,
    }),
    [PageAction, application]
  );
  const onRowEvent: any = useMemo(
    () => (record: any, index: number) => {
      return {
        className: 'group/item',
      };
    },
    []
  );

  return (
    <TablePagination paginationOpts={paginationOptions}>
      {(paginationOpts: PaginationProps) => (
        <Table
          size='small'
          columns={columns}
          dataSource={entities}
          onChange={(params: any) =>
            onPageParamsChange(params, PageAction.setQueryParams)
          }
          pagination={paginationOpts}
          onRow={onRowEvent}
        />
      )}
    </TablePagination>
  );
};

export default ApplicationTable;
